package com.gin.kotlin.gf2gamecommunity.pagingsource

import com.gin.kotlin.form.CommentUserForm
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.livedata.AbstractPagingSource
import com.gin.kotlin.response.comment.UserComment
import retrofit2.await

class CommentUserPagingSource(private val userId: Int) : AbstractPagingSource<UserComment>() {
    lateinit var form: CommentUserForm

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, UserComment> {
        val page = params.key ?: 1
        if (page == 1) form = CommentUserForm(userId)

        try {
            val response = App.INSTANCE.api.commentApi.userList(form).await()

            val commentUserPage = response.data ?: return LoadResult.Page(listOf(), null, null)

            // 修改翻页数据
            form = form.copy(
                createTime = commentUserPage.createTime,
                lastTid = commentUserPage.lastTid
            )
            // 根据响应结果决定是否有下一页
            val nextKey = if (commentUserPage.nextPage) page + 1 else null
            // 返回结果
            return LoadResult.Page(commentUserPage.list, null, nextKey)
        } catch (e: Exception) {
            // 处理异常
            e.printStackTrace()
            return LoadResult.Error(e)
        }

    }

    companion object {
        private val TAG = CommentUserPagingSource::class.java.simpleName
    }
}